package edu.controller;


import edu.support.base.controller.BaseController;
import edu.support.resp.JsonResponse;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.List;

/**
 * 公共请求
 *
 * @date 13:08
 */
@RestController
@RequestMapping("api/common")
public class CommonController extends BaseController {

    /**
     * 上传文件
     *
     * @param file
     * @return
     */
    @RequestMapping("upload")
    public JsonResponse<String> upload(MultipartFile file) {
        String path = saveFile(file);
        return JsonResponse.success(path);
    }

    /**
     * 下载文件
     *
     * @param path
     * @param response
     */
    @GetMapping("download")
    public void download(String path, HttpServletResponse response) {
        // 下载路径
        String filePath = uploadPath + path;
        //待下载文件名
        String fileName = FilenameUtils.getName(path);
        // 设置强制下载不打开
        response.setContentType("application/force-download");
        // 设置文件名
        response.addHeader("Content-Disposition", "attachment;fileName=" + fileName);
        try {
            IOUtils.copy(new FileInputStream(filePath), response.getOutputStream());
        } catch (IOException e) {
            logger.error("下载文件失败", e);
        }
    }
}
